package com.cheer.ba.view.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.cheer.ba.R;
import com.cheer.ba.app.App;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.model.ProvinceModel;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.service.LocationService;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.view.base.CommonAdapter;
import com.cheer.ba.view.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 选择省
 *
 * @author HQ
 *         created at 2017/5/15 0015 10:49
 */
public class ProvinceAreaAty extends BaseCommAty implements AdapterView.OnItemClickListener {

    @BindView(R.id.id_prov_list)
    ListView idProvListView;
    //定位到当前的位置
    private TextView mTvLocation;
    private String mSaveLocation;

    private CommonAdapter<ProvinceModel> mAdapter;
    private List<ProvinceModel> areaList = new ArrayList<ProvinceModel>();

    //定位服务
    private LocationService mLocationService;

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_my_area, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new OilMealPresenter();
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.mine_area));

        View headView = LayoutInflater.from(this).inflate(R.layout.layout_area_head, null);
        mTvLocation = (TextView) headView.findViewById(R.id.tv_location);
        mTvLocation.setText(getString(R.string.locate_loading));
        mTvLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(mSaveLocation) || mSaveLocation.contains("null")) {
                    return;
                }
                if (!StringUtils.isEmpty(mSaveLocation)) {
                    Intent intent = new Intent();
                    intent.putExtra(IntentKey.General.KEY_DATA, mSaveLocation);
                    setResult(IntentCode.Area.PROVINCE_RESULT_CODE, intent);
                    finish();
                }
            }
        });
        idProvListView.addHeaderView(headView);

        // 模拟一个选中城市
        mAdapter = new CommonAdapter<ProvinceModel>(aty, areaList, R.layout.layout_area_item) {
            @Override
            public void convert(ViewHolder helper, ProvinceModel item) {
                if (null != item) {
                    ((TextView) helper.getView(R.id.id_area_text)).setText(item.mProvinceName);
                    ((TextView) helper.getView(R.id.id_area_check)).setText(item.isPChecked ? "已选中" : "");
                }
            }
        };

        idProvListView.setAdapter(mAdapter);
        idProvListView.setOnItemClickListener(this);
    }

    @Override
    public void initData() {
        checkPermissSdcard();

        List<ProvinceModel> provinces = (List<ProvinceModel>) ((OilMealPresenter) presenter).getData(4,false);
        if (null != provinces && !provinces.isEmpty()) {
            areaList.clear();
            areaList.addAll(provinces);
            getAreaList();
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 更新被选中数据
     */
    public void getAreaList() {
        String area = Session.getUser_area();
        String[] array = area.split(" ");

        for (ProvinceModel model : areaList) {
            if (model.mProvinceName.equals(array[0])) {
                model.isPChecked = true;
            } else {
                model.isPChecked = false;
            }
        }
    }

    /**
     * 检测用户定位权限
     */
    private void checkPermissSdcard() {
        String[] perms = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
        if (!mayRequestPermission(perms)) {
            return;
        }
        getLocation();
    }

    @Override
    public void requestPermissionResult(boolean allowPermission) {
        if (allowPermission) {
            getLocation();
        }
    }

    /**
     * 获取定位地址
     */
    public void getLocation() {
        mLocationService = ((App) getApplication()).mLocationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        mLocationService.registerListener(mListener);
        mLocationService.setLocationOption(mLocationService.getDefaultLocationClientOption());
        //定位
        mLocationService.start();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position > 0) {
            Intent intent = new Intent(this, CityAreaAty.class);
            Bundle data = new Bundle();
            data.putSerializable(IntentKey.General.KEY_MODEL, areaList.get(position - 1));
            intent.putExtras(data);
            startActivityForResult(intent, IntentCode.Area.CITY_REQUEST_CODE);
        } else if (position == 0) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentCode.Area.CITY_REQUEST_CODE) {
            if (resultCode == IntentCode.Area.CITY_RESULT_CODE) {
                if (null != data) {
                    String mSaveArea = data.getStringExtra(IntentKey.General.KEY_DATA);
                    Intent intent = new Intent();
                    intent.putExtra(IntentKey.General.KEY_DATA, mSaveArea);
                    setResult(IntentCode.Area.PROVINCE_RESULT_CODE, intent);
                    finish();
                }
            }
        }
    }

    @Override
    protected void onStop() {
        //注销监听
        if (null != mLocationService) {
            mLocationService.unregisterListener(mListener);
            //停止定位服务
            mLocationService.stop();
        }
        super.onStop();
    }

    /*****
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                mSaveLocation = location.getProvince() + " " + location.getCity() + " " + location.getDistrict();
                if (mSaveLocation.contains("null")) {
                    mSaveLocation = "";
                    mTvLocation.setText("定位失败");
                } else {
                    mTvLocation.setText(mSaveLocation);
                }
            }
            mLocationService.stop();
        }

        public void onConnectHotSpotMessage(String s, int i) {
        }
    };
}
